﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Maps.MapControl;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;

namespace PmuRegistry.Silverlight.Pages
{
	public partial class QuickView : Page
	{
		PhasorDataServiceClient m_client;
		Button m_pushPinButton;
		ToolTip m_toolTip;
		ObservableCollection<Device> m_deviceList;
		List<Device> m_filteredList;
		ActivityWindow m_activityWindow;

		public QuickView()
		{
			InitializeComponent();
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetDeviceListCompleted += new EventHandler<GetDeviceListCompletedEventArgs>(client_GetDeviceListCompleted);
			m_client.GetRecentDevicesCompleted += new EventHandler<GetRecentDevicesCompletedEventArgs>(client_GetRecentDevicesCompleted);
			m_client.GetPlannedPmusStatCompleted += new EventHandler<GetPlannedPmusStatCompletedEventArgs>(client_GetPlannedPmusStatCompleted);
			m_client.GetReportingPmusStatCompleted += new EventHandler<GetReportingPmusStatCompletedEventArgs>(client_GetReportingPmusStatCompleted);
			VirtualEarthMap.CredentialsProvider = (Application.Current as App).credentials;
			Loaded += new RoutedEventHandler(QuickView_Loaded);
		}

		void client_GetReportingPmusStatCompleted(object sender, GetReportingPmusStatCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxReportingStats.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Reporting PMUs Stats", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void client_GetPlannedPmusStatCompleted(object sender, GetPlannedPmusStatCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxPlannedStats.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Planned PMUs Stats", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void client_GetRecentDevicesCompleted(object sender, GetRecentDevicesCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxRecentlyAdded.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Recently Added Devices", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void QuickView_Loaded(object sender, RoutedEventArgs e)
		{
			m_activityWindow = new ActivityWindow("Loading Data... Please Wait...");
			m_activityWindow.Show();
		}

		void client_GetDeviceListCompleted(object sender, GetDeviceListCompletedEventArgs e)
		{
			if (e.Error == null)
			{
				m_deviceList = new ObservableCollection<Device>();
				m_filteredList = new List<Device>();
				m_deviceList = e.Result;
				m_filteredList = (from item in m_deviceList
								where item.DeviceStatusName == "Operational" || item.DeviceStatusName == "Out of Service" || item.DeviceStatusName == "Validated"
								select item).ToList();
				LoadMapData();
			}
			else 
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Device List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}

		void LoadMapData()
		{
			double avgLongitude = Convert.ToDouble(m_deviceList.Average(m => m.Longitude));
			double avgLatitude = Convert.ToDouble(m_deviceList.Average(m => m.Latitude));

			foreach (Device device in m_filteredList)
			{
				m_pushPinButton = new Button();
				m_toolTip = new ToolTip();
				m_toolTip.DataContext = device;
				m_toolTip.Template = Application.Current.Resources["MapToolTipTemplate"] as ControlTemplate;
				ToolTipService.SetToolTip(m_pushPinButton, m_toolTip);
				m_pushPinButton.Content = device.CompanyMapAcronym;
				if (device.DeviceStatusName == "Operational")
					m_pushPinButton.Template = Application.Current.Resources["GreenPushPinButtonTemplate"] as ControlTemplate;
				else if (device.DeviceStatusName == "Out of Service")
					m_pushPinButton.Template = Application.Current.Resources["RedPushPinButtonTemplate"] as ControlTemplate;
				else if (device.DeviceStatusName == "Validated")
					m_pushPinButton.Template = Application.Current.Resources["YellowPushPinButtonTemplate"] as ControlTemplate;
				else if (device.DeviceStatusName == "In Progress")
					m_pushPinButton.Template = Application.Current.Resources["BluePushPinButtonTemplate"] as ControlTemplate;
				else if (device.DeviceStatusName == "Planned")
					m_pushPinButton.Template = Application.Current.Resources["WhitePushPinButtonTemplate"] as ControlTemplate;
				else if (device.DeviceStatusName == "Retired")
					m_pushPinButton.Template = Application.Current.Resources["GrayPushPinButtonTemplate"] as ControlTemplate;

				//pushPinButton.SetValue(MapLayer.MapPositionProperty, new Location(Convert.ToDouble(device.Latitude), Convert.ToDouble(device.Longitude)));
				//pushPinButton.SetValue(MapLayer.MapPositionMethodProperty, PositionMethod.Center);
				(VirtualEarthMap.FindName("PushpinLayer") as MapLayer).AddChild(m_pushPinButton, new Location(Convert.ToDouble(device.Latitude), Convert.ToDouble(device.Longitude)));
			}

            if (avgLatitude == 0) avgLatitude = 37.5;
            if (avgLongitude == 0) avgLongitude = -98.6;
			VirtualEarthMap.Center = new Location(avgLatitude, avgLongitude);
			if (m_activityWindow != null)
				m_activityWindow.Close();
		}

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_client.GetDeviceListAsync();
			m_client.GetRecentDevicesAsync();
			m_client.GetReportingPmusStatAsync();
			m_client.GetPlannedPmusStatAsync();
		}

		private void Checkbox_Click(object sender, RoutedEventArgs e)
		{
			m_filteredList = (from item in m_deviceList
							select item).ToList();
			if (!(bool)CheckboxOperational.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "Operational"
								select item).ToList();								
			}
			if (!(bool)CheckboxOutofService.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "Out of Service"
								select item).ToList();
			}
			if (!(bool)CheckboxValidated.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "Validated"
								select item).ToList();
			}
			if (!(bool)CheckboxInProgress.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "In Progress"
								select item).ToList();
			}
			if (!(bool)CheckboxPlanned.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "Planned"
								select item).ToList();
			}
			if (!(bool)CheckboxRetired.IsChecked)
			{
				m_filteredList = (from item in m_filteredList
								where item.DeviceStatusName != "Retired"
								select item).ToList();
			}
			(VirtualEarthMap.FindName("PushpinLayer") as MapLayer).Children.Clear();		//.RemoveAllChildren();
			LoadMapData();
		}

		private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
		{
			string deviceId = ((HyperlinkButton)sender).Tag.ToString();
			NavigationService.Navigate(new Uri("/Pages/Devices/AddNew.xaml?did=" + deviceId, UriKind.Relative));
		}

	}
}
